<template>
  <div>
    <div style="padding: 10px 0">
      <el-input style="width: 200px" placeholder="请输入标题" suffix-icon="el-icon-search" v-model="title"></el-input>
      <el-input style="width: 200px" placeholder="请输入作者" suffix-icon="el-icon-user" class="ml-5" v-model="author"></el-input>
      <el-button class="ml-5" type="success" @click="load">搜索</el-button>
      <el-button class="ml-5" type="warning" @click="reset">重置</el-button>
    </div>

    <div style="margin: 10px 0">
      <el-button type="success" @click="handleAdd">新增 <i class="el-icon-circle-plus-outline"></i></el-button>
      <el-button type="danger" @click="deleteBatch">批量删除 <i class="el-icon-remove-outline"></i></el-button>
      <el-upload action="http://localhost:8082/information/import"
                 :show-file-list="false"
                 accept=".xlsx"
                 :on-success="handleExcelImportSuccess"
                 style="display: inline-block">
        <el-button type="success" class="ml-5">导入 <i class="el-icon-download"></i></el-button>
      </el-upload>
      <el-button type="success" @click="exp" class="ml-5">导出 <i class="el-icon-upload2"></i></el-button>
    </div>

    <el-table :data="tableData" border stripe header-cell-class-name="headerBg"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="title" label="标题"></el-table-column>
      <el-table-column prop="date"  label="日期" width="150"></el-table-column>
      <el-table-column prop="author" label="作者"></el-table-column>
      <el-table-column prop="cover" label="封面">
        <template slot-scope="scope">
          　<img :src="scope.row.cover" width="100" height="100" class="head_pic"/>
        </template>
      </el-table-column>
      <el-table-column prop="content" label="内容" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <div v-html="scope.row.content" style="height:150px"></div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180px">
        <template slot-scope="scope">
          <el-button type="success" @click="handleEdit(scope.row)">编辑 <i class="el-icon-edit"></i></el-button>
          <el-button type="danger" @click="del(scope.row.id)">删除 <i class="el-icon-remove-outline"></i></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="padding: 10px 0">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[2, 5, 10, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

    <el-dialog title="文章信息" :visible.sync="dialogFormVisible" width="60%">
      <el-form label-width="80px" size="small">
        <el-form-item label="标题">
          <el-input v-model="form.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="作者">
          <el-input v-model="form.author" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="封面">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:8082/file/upload"
            :show-file-list="false"
            :on-success="handleCoverSuccess">
            <img v-if="form.cover" :src="form.cover" style="width: 100px; height: 100px" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="内容">
          <div>
            <el-upload
              style="display:none"
              :action="uploadURL + '/tool/Upload/UploadImages'"
              :show-file-list="false"
              :on-success="drugAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              accept=".jpg, .jpeg, .png, .JPG, .JPEG, .bmp"
              :on-error="handleAvatarError"
              id="uploadImg"
              ref="uploadImg"
            >
            </el-upload>
            <!--          这里是结合elemen UI进行图片上传，保存图片地址至服务器，-->
            <!--          而不是将图片流存入服务器，节省空间-->
            <quill-editor
              v-model="form.content"
              ref="myQuillEditor"
              :options="editorOption"
              @blur="onEditorBlur($event)"
              @focus="onEditorFocus($event)"
              @change="onEditorChange($event)"
            >
            </quill-editor>
          </div>
<!--          <el-input type="textarea" v-model="form.content" autocomplete="off"></el-input>-->
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="success" @click="save">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {formatDate} from "../utils/formatDate";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import { quillEditor } from "vue-quill-editor";

export default {
  name: "Information",
  data() {
    return {
      tableData: [],
      total: 0,
      pageNum: 1,
      pageSize: 10,
      title: "",
      author: "",
      dialogFormVisible: false,
      form: {},
      multipleSelection: [],
      headerBg: 'headerBg',
      uploadURL: "",
      changeHosform: {
        details: ""
      },
    }
  },
  editorOption: {
      placeholder: "请在这里输入", //默认显示文字
        modules: {
            toolbar: {
              container: [ //头部组件使用工具
                [{header: 1}], // 标题，键值对的形式；1、2表示字体大小
                ["bold", "italic", "underline", "strike"], //加粗，斜体，下划线，删除线
                ["blockquote"], //引用，代码块
                [{list: "ordered"}, {list: "bullet"}], //列表
                [{direction: "rtl"}], // 文本方向
                [{size: ["small", "large", "huge"]}], // 字体大小
                [{header: [1, 2, 3, 4, 5, 6]}], //几级标题
                [{align: []}], //对齐方式
                ["image"] //上传图片、上传视频
              ],
              handlers: {
                image: function (value) {
                  if (value) {
                    // 调用iview图片上传，改为element图片上传方法
                    document.querySelector("#uploadImg .el-upload").click();
                  } else {
                    this.quill.format("image", false);
                  }
                }
              }
            }
        }
  },
  components: { quillEditor },
  created() {
    //请求分页查询数据
    this.load()
  },
  filters: {
    formatDate(val){
      return formatDate(val)
    }
  },
  methods: {
    load() {
      this.request.get("/information/page", {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          title: this.title,
          author: this.author
        }
      }).then(res => {
        console.log(res)
        this.tableData = res.data
        this.total = res.total
      })
    },
    save() {
      this.request.post("/information/edit", this.form).then(res => {
        if (res) {
          this.$message.success("保存成功")
          this.dialogFormVisible = false
          this.load()
        } else {
          this.$message.error("保存失败")
        }
      })
    },
    handleAdd() {
      this.dialogFormVisible = true
      this.form = {}
    },
    handleEdit(row) {
      this.form = Object.assign({}, row)
      this.dialogFormVisible = true
    },
    del(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.request.delete("/information/del?id=" + id).then(res => {
          if (res) {
            this.$message.success("删除成功")
            this.load()
          } else {
            this.$message.error("删除失败")
          }
        })
      });
    },
    handleSelectionChange(val) {
      console.log(val)
      this.multipleSelection = val
    },
    deleteBatch() {
      let ids = this.multipleSelection.map(v => v.id) //将对象数组变成纯id数组 [{},{},{}] => [1,2,3]
      this.$confirm('此操作将永久批量删除选中数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.request.delete("/information/delBatch", {data: ids}).then(res => {
          if (res) {
            this.$message.success("批量删除成功")
            this.load()
          } else {
            this.$message.error("批量删除失败")
          }
        })
      });
    },
    reset() {
      this.title = ""
      this.author = ""
      this.load()
    },
    handleSizeChange(pageSize) {
      console.log(pageSize)
      this.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(pageNum) {
      console.log(pageNum)
      this.pageNum = pageNum
      this.load()
    },
    exp() {
      window.open("http://localhost:8082/information/export")
    },
    handleExcelImportSuccess() {
      this.$message.success("导入成功")
      this.load()
    },
    //封面上传成功
    handleCoverSuccess(res){
      this.form.cover = res
    },
    //图片上传成功之后的回调
    handleAvatarSuccess(res, file) {
      let resp = res;
      console.log(resp);
      if (resp.code === 200) {
        this.changeHosform.imageUrl = resp.data[0].filePath;
        console.log(this.changeHosform);
      } else {
        this.$message.error(resp.message);
      }
    },
    //富文本框图片上传成功回调
    drugAvatarSuccess(res, file) {
      // 获取富文本组件实例
      let quill = this.$refs.myQuillEditor.quill;
      // 如果上传成功
      if (res) {
        // 获取光标所在位置
        let length = quill.getSelection().index;
        // 插入图片，res为服务器返回的图片链接地址
        quill.insertEmbed(length, "image", res.data[0].filePath);
        // 调整光标到最后
        quill.setSelection(length + 1);
      } else {
        // 提示信息，需引入Message
        this.$message.error("图片插入失败");
      }
    },
    //图片上传失败回调
    handleAvatarError(err, file, fileList) {
      // console.log(err, file, fileList);
      this.$message.error("图片上传失败，请重新选择!!!");
    },
    //判断是否是图片
    isImage(fileName) {
      if (typeof fileName !== "string") return;
      let name = fileName.toLowerCase();
      return (
        name.endsWith(".png") ||
        name.endsWith(".jpeg") ||
        name.endsWith(".jpg") ||
        name.endsWith(".bmp") ||
        name.endsWith(".PNG") ||
        name.endsWith(".JPEG") ||
        name.endsWith(".JPG") ||
        name.endsWith(".BMP")
      );
    },
    onEditorBlur() {}, // 失去焦点事件
    onEditorFocus() {}, // 获得焦点事件
    onEditorChange() {}, // 内容改变事件
  }
}
</script>

<style scoped>

</style>
